package com.csx.micrometer.invoke.custom;

import com.csx.micrometer.invoke.constant.InvokeConstant;
import com.csx.micrometer.invoke.context.MicrometerRequest;
import com.csx.micrometer.invoke.context.MicrometerResponse;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;

import java.net.URL;


/**
 * @author cuisongxu
 * @date 2022/12/1 14:26
 */
public class DefaultTagsCustom implements TagsCustom {

    private final Logger logger = LoggerFactory.getLogger(DefaultTagsCustom.class);

    @Override
    public Tags customTags(MicrometerRequest request, @Nullable MicrometerResponse response, Tags tags) {

        try {

            // 服务名
            URL url = new URL(request.getRequestURL().toString());
            String application = url.getHost();

            // 资源名
            String resource = request.getRequestURI();

            // 请求方法
            String requestMethod = request.getMethod();

            // 封装Tags
            Tag applicationTag = Tag.of(InvokeConstant.APPLICATION, application);
            Tag resourceTag = Tag.of(InvokeConstant.API, resource);
            Tag methodTag = Tag.of(InvokeConstant.REQUEST_METHOD, requestMethod);

            tags = Tags.of(applicationTag, resourceTag, methodTag);
        }catch (Exception e) {
            logger.warn("default tags custom failed because: ", e);
        }

        logger.info("default tags custom result: " + tags.toString());
        return tags;
    }

    /**
     * 最先执行，后面的可以覆盖掉该默认的
     * @return 定义
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}
